var $clueFollowTable = $('#clue_follow_list_table');
var $clueVisiteTable = $('#clue_visite_list_table');
var $addPeopleListTable = $('#add_people_list_table');
$(function () {
    $('#followUpContent').css('display', 'block');
    $('#visitContent').css('display', 'none');
    $('#notesContent').css('display', 'none');
    $('#replenishContent').css('display', 'none');
    selectClueFollowTabList();

    $('.tagsinput').on('itemAdded', function(event) {
        // 添加标签
        var tagStr = $(this).val();
        updateUserClueTag(tagStr)
    }).on('itemRemoved', function(event) {
        var tagStr = $(this).val();
        // 删除标签
        updateUserClueTag(tagStr)
    })

    // 返回按钮功能
    $('#backBtn').on('click', function () {
        var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
        var navTab = parent.$multitabs._getNavTab($thisTabs);
        closeTab(navTab);
        // openTab("线索清单", "/front/user/myClueDetail?poolId=" + $("#poolId").val() + "&defaultMark=0&capacity=300");
        refreshActivePane('/front/user/myClueDetail?poolId=' + $("#poolId").val() + "&defaultMark=0&capacity=300");
        delStorageAndRemove(navTab);
    })

    // 编辑弹窗
    $('#editInfo').on('click', function () {
        infoModalEcho();
    });

});

//防止表头与表格不对齐
$(window).resize(function () {
    $clueFollowTable.bootstrapTable('resetView');
    $clueVisiteTable.bootstrapTable('resetView');
    $addPeopleListTable.bootstrapTable('resetView');
});


function  changeTable(str) {
    if (str == 'followUp') {//跟进记录
        $('#followUp').addClass('active')
        $('#followUp').siblings().removeClass('active')
        $('#followUpContent').css('display', 'block');
        $('#visitContent').css('display', 'none');
        $('#notesContent').css('display', 'none');
        $('#replenishContent').css('display', 'none');
        $("#tabType").val('1');
        selectClueFollowTabList();
    }
    if (str == 'visit') {//拜访记录
        $('#visit').addClass('active')
        $('#visit').siblings().removeClass('active')
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'flex');
        $('#notesContent').css('display', 'none');
        $('#replenishContent').css('display', 'none');
        $("#tabType").val('2');
        selectVisitTabList();
    }
    if (str == 'company') {//公司资料
        $('#company').addClass('active')
        $('#company').siblings().removeClass('active')
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'none');
        $('#notesContent').css('display', 'block');
        $('#replenishContent').css('display', 'none');
        $("#tabType").val('3');
    }
    if (str == 'addpeople') {//新增联系人
        $('#addpeople').addClass('active')
        $('#addpeople').siblings().removeClass('active')
        $('#followUpContent').css('display', 'none');
        $('#visitContent').css('display', 'none');
        $('#notesContent').css('display', 'none');
        $('#replenishContent').css('display', 'block');
        $("#tabType").val('4');
        selectAddPeopleList();
    }
}

/**
 * 跟进记录tab页列表信息
 */
function selectClueFollowTabList(){
    //先销毁表格
    $clueFollowTable.bootstrapTable('destroy');
    $clueFollowTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/userClueRecord',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'followTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueFollowId',
        idField: 'clueFollowId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueFollowId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
           /* {title: '跟进人',field: 'followPeopleName',align: 'center', valign: 'middle'},*/
            {title: '跟进方式', field: 'followWay', align: 'center', valign: 'middle', formatter: followWayFormat},
            {title: '跟进时间', field: 'followTm', align: 'center', valign: 'middle'},
            {title: '客户意向(百分比)', field: 'customerIntention', align: 'center', valign: 'middle'},
            {title: '客户质量', field: 'customerQuality', align: 'center', valign: 'middle', formatter: customerQualityFormat},
            {title: '跟进详情', field: 'followDetail',align: 'center', valign: 'middle'},
            {title: '线索评分（0-10分）', field: 'clueScore', align: 'center', valign: 'middle'},
            {title: '沟通时长(秒)', field: 'communicationTime', align: 'center', valign: 'middle'},
            /*{title: '帮助说明', field: 'remark', align: 'center', valign: 'middle'},*/
            /*{title: '下次计划时间', field: 'nextPlanTime', align: 'center', valign: 'middle'},*/
            {title: '跟进目的', field: 'followPurpose', align: 'center', valign: 'middle', formatter: followPurposeFormat}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

function infoModalEcho() {
    $('#companyName').val(clue.companyName);
    $('#contactPerson').val(clue.contactPerson);
    if(clue.sex == '0'){
        $("#man").attr('checked', 'checked');
    } else {
        $("#femal").attr('checked', 'checked');
    }
    $('#contactPersonPhone').val(clue.contactPersonPhone);
    $('#companyEmail').val(clue.companyEmail);
    $('#job').val(clue.job);
    $('#rating').selectpicker('val', clue.rating);
    $('#source').selectpicker('val', clue.source);
    $('#clientCategories').selectpicker('val', clue.clientCategories);
    $('#clientLevel').selectpicker('val', clue.clientLevel);
    $('#unifiedSocialCreditCode').val(clue.unifiedSocialCreditCode);
    $('#industry').selectpicker('val', clue.industry);
    $('#companySize').selectpicker('val', clue.companySize);
    $('#companyType').selectpicker('val', clue.companyType);
    $('#capitalType').selectpicker('val', clue.capitalType);
    $('#enterpriseState').selectpicker('val', clue.enterpriseState);
    $('#legalRepresentative').val(clue.legalRepresentative);
    $('#registrationNumber').val(clue.registrationNumber);
    $('#registeredCapital').val(clue.registeredCapital);
    $('#organizationCode').val(clue.organizationCode);
    $('#legalRepresentative').val(clue.legalRepresentative);
    $('#insuredNumber').val(clue.insuredNumber);
    $('#importAndExportEnterpriseCode').val(clue.importAndExportEnterpriseCode);
    $('#registrationAuthority').val(clue.registrationAuthority);
    $('#paidInCapital').val(clue.paidInCapital); // 实缴资本
    $('#taxpayerIdentificationNumber').val(clue.taxpayerIdentificationNumber);
    $('#businessRegistrationNumber').val(clue.businessRegistrationNumber);
    $('#enterpriseExternalPhone').val(clue.enterpriseExternalPhone);
    $('#enterpriseExternalLandline').val(clue.enterpriseExternalLandline);
    $('#companyWebsite').val(clue.companyWebsite);
    $("#registrationTime").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    })
    $('#registrationTime').datepicker('setDate', clue.registrationTime);
    //核准日期
    $("#approvedDate").datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#approvedDate').datepicker('setDate', clue.approvedDate);
    // 成立日期
    $('#establishmentDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#establishmentDate').datepicker('setDate', clue.establishmentDate);
    $('#wechat').val(clue.wechat);
    $('#companyAddress').val(clue.companyAddress);
    getProvince(clue.provinceId); // 修改页面获取省份数据
    $('#province').selectpicker('val', clue.provinceId);
    $('#city').selectpicker('val', clue.cityId);
    $('#businessScope').val(clue.businessScope);
    $('#remark').val(clue.remark);
    $('#staticPath2').val(clue.tag);

    // $('#editInfoForm').bootstrapValidator('resetForm');
}

/**
 * 拜访记录tab页列表信息
 */
function selectVisitTabList(){
    //先销毁表格
    $clueVisiteTable.bootstrapTable('destroy');
    $clueVisiteTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/userClueRecord',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'updateTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueVisitRecordId',
        idField: 'clueVisitRecordId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueVisitRecordId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle',formatter: indexFormat},
            {title: '类别', field: 'type', align: 'center', valign: 'middle',formatter: typeFormat},
            {title: '跟进日期',field: 'createTm',align: 'center', valign: 'middle'},
            {title: '拜访人',field: 'accompanyVisitPeople',align: 'center', valign: 'middle'},
            {title: '联系方式',field: 'contactInformation',align: 'center', valign: 'middle'},
            {title: '拜访地址',field: 'visitAddress',align: 'center', valign: 'middle'},
            {title: '沟通时长(分)',field: 'communicationTime',align: 'center', valign: 'middle',formatter: TimeFormat},
            {title: '拜访详情',field: 'visitDetail',align: 'center', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
                   if(data.rows[0] != undefined){
                       $("#imgUrl").attr('src',data.rows[0].imgUrl);
                   }
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 新增联系人记录tab页列表信息
 */
function selectAddPeopleList(){
    //先销毁表格
    $addPeopleListTable.bootstrapTable('destroy');
    $addPeopleListTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        //请求地址
        url: '/clue/userClueRecord',
        //请求方式
        method: 'post',
        //请求内容类型
        contentType: "application/x-www-form-urlencoded",
        //数据类型
        dataType: "json",
        //是否显示行间隔色
        striped: true,
        //是否启用排序
        sortable: true,
        //排序方式
        sortOrder: "desc",
        sortName: 'updateTm',
        //是否使用缓存
        cache: false,
        //每行的唯一标识
        uniqueId: "id",
        //显示隐藏列
        showColumns: false,
        //显示刷新按钮
        showRefresh: false,
        //切换显示样式
        showToggle: false,
        //显示Table脚部
        showFooter: false,
        //是否显示分页
        pagination: true,
        //是否显示分页按钮
        showPaginationSwitch: false,
        //是否启用点击选中行
        clickToSelect: false,
        singleSelect: false,
        //最少要显示的列数
        minimumCountColumns: 2,
        //cell没有值时显示
        undefinedText: '',
        //分页方式：client客户端分页，server服务端分页
        sidePagination: "server",
        uniqueId: 'clueContactId',
        idField: 'clueContactId',
        //每页的记录行数
        pageSize: 5,
        //初始化加载第1页，默认第1页
        pageNumber: 1,
        //可供选择的每页的行数
        pageList: "[10, 20, 50]",
        //查询参数
        queryParams: queryParams,
        columns: [
            {title: '主键', field: 'clueContactId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'middle', formatter: indexFormat},
            {title: '姓名', field: 'contactName', align: 'center', valign: 'middle'},
            {title: '联系方式', field: 'contactInformation', align: 'center', valign: 'middle'},
            {title: '职务', field: 'contactJob', align: 'center', valign: 'middle'}
        ],
        responseHandler: function (result) {
            if (result.code == "000000")
            {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        }, formatNoMatches: function () {
            return '无符合条件的记录';
        }
    });
}

/**
 * 拼接表格查询条件参数
 */
function queryParams(params) {
    params.pageSize = params.limit;//分页大小
    params.pageIndex = (params.offset / params.limit) + 1;
    params.clueId = $.trim($('#clueId').val());
    params.tabType = $("#tabType").val();
    return params;
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

function typeFormat(value, row, index) {
    if (1 == value) {
        return "拜访";
    } else{
        return "陪访";
    }
}

function TimeFormat(value, row, index) {
    var time = value/60;
    return time;
}

/**
 * 跟进方式：1-电话；2-拜访
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function followWayFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "";
    } else if (1 == value) {
        return "线上电话";
    } else if (2 == value) {
        return "拜访";
    } else if (3 == value) {
        return "微信";
    } else if (4 == value) {
        return "线下电话";
    } else if (5 == value) {
        return "邮箱";
    } else if (6 == value) {
        return "陪访";
    }
}

/**
 * 客户质量:1-优；2:良；3:一般
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerQualityFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "";
    } else if (1 == value) {
        return "优";
    } else if (2 == value) {
        return "良";
    } else if (3 == value) {
        return "一般";
    }
}


/**
 * 跟进目的 1-跟进产品；2-过程管理
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function followPurposeFormat(value, row, index) {
    if (value == null || value == undefined) {
        return "";
    } else if (1 == value) {
        return "产品跟进";
    } else if (2 == value) {
        return "过程跟进";
    }
}

// 新增联系人弹框
function addPeople() {
    //联系人姓名
    $("#contact_name").val('');
    //职务
    $("#contact_job").val('');
    //联系方式
    $("#contact_information").val('');
    $("#peopleModel").modal("show");
}

// 新增联系人
function insertPeople() {
    //联系人姓名
    var contactName = $("#contact_name").val();
    //职务
    var contactJob = $("#contact_job").val();
    //联系方式
    var contactInformation = $("#contact_information").val();
    //线索id
    var clueId = $.trim($('#clueId').val());

    //联系人姓名为空和长度验证
    if (!contactName) {
        ok = false;
        promptInfo("联系人姓名不能为空!");
        return;
    } else {
        if (contactName.length > 10) {
            ok = false;
            promptInfo("联系人姓名长度不能大于10个字！");
            return;
        }
    }


    //联系方式为空验证
    if (!contactInformation) {
        ok = false;
        promptInfo("联系方式不能为空!");
        return;
    }



    var jsonData = {
        contactName: contactName,
        contactJob: contactJob,
        contactInformation: contactInformation,
        clueId: clueId
    };

    $.ajax({
        url: '/clueContact/save/clueContact',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if (data.code == "000000") {
                $.alert("保存成功！");
                $("#peopleModel").modal("hide");
                $addPeopleListTable.bootstrapTable('refresh');
            }else {
                alert("保存失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });



}

//转化为客户
function convertToCustomer() {
    var clueId = $.trim($('#clueId').val());
    $.ajax({
        url: '/customerController/convertToCustomer',
        type: 'POST',
        dataType: "json",
        data: {
            clueId : clueId
        },
        success: (function (data) {
            if (data.code == "000000") {
                $.alert("转化成功！");
            } else if (data.code == "CF0001") {
                $.alert("这个线索已经转化过客户了!!!");
            } else if (data.code == "CF0002") {
                $.alert("您已经有175个非会员客户了,不能转化客户!!!");
            } else if (data.code == "CF0004") {
                $.alert("客户名称已关联客户,不能转化客户!!!");
            } else if (data.code == "C00030") {
                $.alert("企业客户信息错误,请核实!!!");
            } else {
                alert("保存失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}


function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}



//-----------------------修改页面----------------------------
// 渲染城市列表
function getProvince() {
    let provinceNames = [];
    $.each(cityJson[0], function(key, value){
        provinceNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#province').html(provinceNames.join(''));
    getCity('110000');
}

// 根据省获取市
function getCity(provinceId) {
    $('#city').html('');
    let key = '0,'+ provinceId;
    let cityNames = [];
    $.each(cityJson[key], function(key, value){
        cityNames.push('<option value="' + key + '">' + value + '</option>')
    });
    $('#city').html(cityNames.join(''));
}

// '切换城市'
function changeCity() {
    console.log($('#province').val())
    getCity($('#province').val())
}

// 保存数据
function editClue() {
    //公司名称
    var companyName = $.trim($("#companyName").val());

    //联系人
    var contactPerson = $.trim($("#contactPerson").val());

    //联系电话
    var contactPersonPhone = $.trim($("#contactPersonPhone").val());

    //性别
    var sex = $("input[name='sex']:checked").val();

    //公司邮箱
    var companyEmail = $.trim($("#companyEmail").val());

    //职务
    var job = $.trim($("#job").val());

    //线索评级
    var rating = $('#rating').val();

    //线索来源
    var source = $.trim($("#source").val());

    //客户类别
    var clientCategories = $('#clientCategories').val();

    //客户级别
    var clientLevel = $('#clientLevel').val();

    //社会信用码
    var unifiedSocialCreditCode = $.trim($('#unifiedSocialCreditCode').val());

    //行业
    var industry = $.trim($('#industry').val());

    //公司规模
    var companySize = $('#companySize').val();

    //公司网址
    var companyWebsite = $.trim($('#companyWebsite').val());

    //注册号
    var registrationNumber = $.trim($('#registrationNumber').val());

    //组织机构代码
    var organizationCode = $.trim($('#organizationCode').val());

    //公司类型
    var companyType = $('#companyType').val();

    //法定代表人
    var legalRepresentative = $.trim($('#legalRepresentative').val());

    //对外手机
    var enterpriseExternalPhone = $.trim($('#enterpriseExternalPhone').val());

    //对外座机
    var enterpriseExternalLandline = $.trim($('#enterpriseExternalLandline').val());

    //注册资本
    var registeredCapital = $.trim($('#registeredCapital').val());

    //经营范围
    var businessScope = $.trim($('#businessScope').val());

    //注册时间
    var registrationTime = $.trim($('#registrationTime').val());

    //资本类型
    var capitalType = $.trim($('#capitalType').val());

    //企业状态
    var enterpriseState = $('#enterpriseState').val();

    //参保人数
    var insuredNumber =  $.trim($('#insuredNumber').val());

    //微信
    var wechat = $.trim($('#wechat').val());

    //备注
    var remark = $.trim($('#remark').val());

    //工商注册号
    var businessRegistrationNumber = $.trim($('#businessRegistrationNumber').val());

    //实缴资本
    var paidInCapital = $.trim($('#paidInCapital').val());

    //纳税人识别号
    var taxpayerIdentificationNumber = $.trim($('#taxpayerIdentificationNumber').val());

    //登记机关
    var registrationAuthority = $.trim($('#registrationAuthority').val());

    //核准日期
    var approvedDate = $('#approvedDate').val();

    //成立日期
    var establishmentDate = $('#establishmentDate').val();

    //进出口企业代码
    var importAndExportEnterpriseCode = $.trim($('#importAndExportEnterpriseCode').val());

    //企业地址
    var companyAddress = $.trim($('#companyAddress').val());

    //线索标签
    // var tagStr = $('.fm-button').text().split(' ').join(',');
    var tagStr = $.trim($('#staticPath2').val()).replaceAll(/\s+|，+/g, ',').replaceAll(/,+/g, ',');
    var tagStrNew = tagStr.substring(0, tagStr.lastIndexOf(',')) + tagStr.substring(tagStr.lastIndexOf(',') + 1);
    var tag = tagStrNew;

    //省份id
    var provinceId = $('#province').val();

    //省份名称
    var provinceName = $("#province").find("option:selected").text();

    //城市id
    var cityId = $('#city').val();

    //城市名称
    var cityName = $("#city").find("option:selected").text();

    //公司名称为空和长度验证
    if (!companyName) {
        promptInfo("公司名称不能为空!");
        return;
    } else {
        if (companyName.length > 20) {
            promptInfo("公司名称长度不能大于20个字！");
            return;
        }
    }

    //联系人
    if (!contactPerson) {
        promptInfo("联系人不能为空!");
        return;
    }

    //线索来源
    if (!source) {
        promptInfo("线索来源不能为空!");
        return;
    }



    //联系人电话
    /*        if (contactPersonPhone.length > 64) {
                ok = false;
                promptInfo("联系电话长度不能大于64个字符！");
                return;
            } else {
                let reg = /^1[3|4|5|7|8][0-9]{9}$/;
                if (!reg.test(contactPersonPhone)) {
                    ok = false;
                    promptInfo("联系电话不存在！");
                    return;
                }
            }*/

    // 公司邮箱
    if (companyEmail.length > 64) {
        promptInfo("电子邮件长度不能大于64个字符！");
        return;
    } else if(64 > companyEmail.length && companyName.length > 1){
        let reg = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (!reg.test(companyEmail)) {
            promptInfo("请输入正确的邮箱格式！");
            return;
        }
    }

    // 注册资本
    if (registeredCapital) {
        let reg = /^(((0|([1-9]+))\.[0-9]*[1-9][0-9]*)|([1-9]*[1-9][0-9]*\.[0-9]+)|([1-9]*[1-9][0-9]*))$/;
        if (!reg.test(registeredCapital)) {
            promptInfo("请输入正确的金额！");
            return;
        }
    }

    // 实缴资本
    if (paidInCapital) {
        let reg = /^(((0|([1-9]+))\.[0-9]*[1-9][0-9]*)|([1-9]*[1-9][0-9]*\.[0-9]+)|([1-9]*[1-9][0-9]*))$/;
        if (!reg.test(paidInCapital)) {
            promptInfo("请输入正确的金额！");
            return;
        }
    }

    //社会信用码
    if (!unifiedSocialCreditCode) {
        promptInfo("社会信用码不能为空!");
        return;
    } else if (unifiedSocialCreditCode.length > 20||unifiedSocialCreditCode.length <15) {
        promptInfo("社会信用码长度在15-20位以内！");
        return;
    }

    clue.companyName = companyName;
    clue.contactPerson = contactPerson;
    clue.contactPersonPhone = contactPersonPhone;
    clue.sex = sex;
    clue.companyEmail = companyEmail;
    clue.job = job;
    clue.rating = rating;
    clue.source = source;
    clue.clientCategories = clientCategories;
    clue.clientLevel = clientLevel;
    clue.unifiedSocialCreditCode = unifiedSocialCreditCode;
    clue.industry = industry;
    clue.companySize = companySize;
    clue.companyWebsite = companyWebsite;
    clue.registrationNumber = registrationNumber;
    clue.organizationCode = organizationCode;
    clue.companyType = companyType;
    clue.legalRepresentative = legalRepresentative;
    clue.enterpriseExternalPhone = enterpriseExternalPhone;
    clue.enterpriseExternalLandline = enterpriseExternalLandline;
    clue.registeredCapital = parseFloat(registeredCapital);
    clue.businessScope = businessScope;
    clue.registrationTime = registrationTime;
    clue.capitalType = capitalType;
    clue.enterpriseState = enterpriseState;
    clue.insuredNumber = insuredNumber;
    clue.wechat = wechat;
    clue.remark = remark;
    clue.businessRegistrationNumber = businessRegistrationNumber;
    clue.paidInCapital = parseFloat(paidInCapital);
    clue.taxpayerIdentificationNumber = taxpayerIdentificationNumber;
    clue.registrationAuthority = registrationAuthority;
    clue.approvedDate = approvedDate;
    clue.establishmentDate = establishmentDate;
    clue.importAndExportEnterpriseCode = importAndExportEnterpriseCode;
    clue.companyAddress = companyAddress;
    clue.tag = tag;
    clue.provinceId = provinceId;
    clue.provinceName = provinceName;
    clue.cityId = cityId;
    clue.cityName = cityName;

    $.ajax({
        url: '/clue/editClue',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(clue),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $('#editModel').modal('hide');
                                refreshActivePane("/front/cluePoolManager/user/clueDetail?clueId=" + clue.clueId);
                            }
                        }
                    }
                });
            } else if (data.code == 'C00020') {
                //线索名称重复
                promptInfo(data.message);
            } else {
                promptInfo("修改失败");
            }
        }),
        error: (function (res) {
            promptInfo("修改失败");
        })
    })
}

// 修改标签
function updateUserClueTag(val) {
    var json = {
        "tag": val,
        "clueId": clue.clueId
    }
    $.ajax({
        url: '/clue/updateUserClueTag',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(json),
        success: (function (data) {
            if(data.code == '000000'){
                refreshActivePane("/front/cluePoolManager/user/clueDetail?clueId=" + clue.clueId);
            } else {
                promptInfo("操作失败");
            }
        }),
        error: (function (res) {
            promptInfo("操作失败");
        })
    })
}